﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Easy.Common.RegisterType;
using Easy.Plugin.Interface;
using Easy.ServiceLocator.Unity;
using Easy.ServiceLocator.Unity.Interceptor;

namespace Easy.Plugin.Managers
{
    class RegisterTypePluginManager : PluginRootManager
    {
        [ImportMany]
        IEnumerable<Lazy<IRegisterTypePlugin>> _registerTypeAnalysers;
        private PluginRootManager _pluginManager;


        public RegisterTypePluginManager(PluginRootManager pluginManager)
            : base(pluginManager.PluginData)
        {
            _pluginManager = pluginManager;
        }

        public override void Run()
        {
            RunParent();

            RunMe();
        }


        #region private

        private void RunParent()
        {
            _pluginManager.Run();

            _pluginManager.Container.ComposeParts(this);

            base.Container = _pluginManager.Container;
        }

        private void RunMe()
        {
            if (_registerTypeAnalysers == null)
            {
                return;
            }

            var regInfolst = new List<RegisterTypeInfo>();

            foreach (var analyser in _registerTypeAnalysers)
            {
                var result = analyser.Value.Analyze();

                regInfolst.AddRange(result);
            }

            //自动注册容器
            EasyUnity.AutoRegisterType(regInfolst);

            //配置默认拦截器
            EasyDefaultInterceptor.Configure(regInfolst.Select(r => r.Assembly).Distinct().ToList());
        }

        #endregion
    }
}
